﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Abhimanu.Mobile.Models;
using Abhimanu.Mobile.DB;

namespace Abhimanu.Mobile.Controllers
{
    public class FacultyController : Controller
    {
        public ActionResult Home()
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            ActivityModel model = new ActivityModel();
            model.Activities = new List<ActivityItem>();
            model.Activities = new List<ActivityItem>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var result = (from obj in dataContext.MemberActivities
                              join u in dataContext.UserInfos
                              on obj.UserID equals u.UserID
                              orderby obj.CreatedDate descending
                              select new { obj.ActivityID, obj.ActText, obj.CommentCount, obj.CreatedDate, u.FirstName, u.LastName }).Take(20);
                foreach (var item in result)
                {
                    model.Activities.Add(new ActivityItem()
                    {
                        ActivityID = item.ActivityID,
                        ActText = item.ActText,
                        CommentCount = item.CommentCount,
                        PostBy = string.Format("{0} {1}", item.FirstName, item.LastName),
                        PostTime = GetTimeAgo(item.CreatedDate)
                    });
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Home(ActivityModel model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            model.Activities = new List<ActivityItem>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                MemberActivity memberActivity = new MemberActivity()
                {
                    ActText = model.SaySomething,
                    CommentCount = 0,
                    LikeCount = 0,
                    CreatedDate = DateTime.Now,
                    UserID = userId
                };

                dataContext.MemberActivities.InsertOnSubmit(memberActivity);
                dataContext.SubmitChanges();
                var result = (from obj in dataContext.MemberActivities
                              join u in dataContext.UserInfos
                              on obj.UserID equals u.UserID
                              orderby obj.CreatedDate descending
                              select new { obj.ActivityID, obj.ActText, obj.CommentCount, obj.CreatedDate, u.FirstName, u.LastName }).Take(20);
                foreach (var item in result)
                {
                    model.Activities.Add(new ActivityItem()
                    {
                        ActivityID = item.ActivityID,
                        ActText = item.ActText,
                        CommentCount = item.CommentCount,
                        PostBy = string.Format("{0} {1}", item.FirstName, item.LastName),
                        PostTime = GetTimeAgo(item.CreatedDate)
                    });
                }
            }

            return View(model);
        }

        private string GetTimeAgo(DateTime createdDate)
        {
            string timeAgo = "";
            TimeSpan ts = DateTime.Now - createdDate;
            if (ts.Days > 0)
            {
                timeAgo = string.Format("{0} days", ts.Days);
            }
            else if (ts.Hours > 0)
            {
                timeAgo = string.Format("{0} hrs", ts.Hours);
            }
            else if (ts.Minutes > 0)
            {
                timeAgo = string.Format("{0} mins", ts.Minutes);
            }
            else if (ts.Seconds > 0)
            {
                timeAgo = string.Format("{0} secs", ts.Seconds);
            }

            return timeAgo;
        }

        public ActionResult ActivityComment(long activityId)
        {
            ActivityItem model = new ActivityItem();
            model.Comments = new List<ActivityCommentModel>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                MemberActivity activity = dataContext.MemberActivities.Where(obj => (obj.ActivityID == activityId)).ToList()[0];
                var result = (from obj in dataContext.ActivityComments
                              join u in dataContext.UserInfos
                              on obj.UserID equals u.UserID
                              orderby obj.CreatedDate descending
                              where obj.ActivityID == activityId
                              select new { obj.CommentID, obj.CommentText, obj.CreatedDate, u.FirstName, u.LastName });
                foreach (var item in result)
                {
                    model.Comments.Add(new ActivityCommentModel()
                    {
                        CommentID = item.CommentID,
                        CommentText = item.CommentText,
                        CommentedBy = string.Format("{0} {1}", item.FirstName, item.LastName),
                        TimeAgo = GetTimeAgo(item.CreatedDate)
                    });
                }

                model.ActText = activity.ActText;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult ActivityComment(ActivityItem model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            model.Comments = new List<ActivityCommentModel>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                MemberActivity activity = dataContext.MemberActivities.Where(obj => (obj.ActivityID == model.ActivityID)).ToList()[0];

                ActivityComment comment = new DB.ActivityComment()
                {
                    ActivityID = model.ActivityID,
                    CommentText = model.CommentText,
                    CreatedDate = DateTime.Now,
                    UserID = userId
                };

                activity.CommentCount = activity.CommentCount + 1;
                dataContext.ActivityComments.InsertOnSubmit(comment);
                dataContext.SubmitChanges();


                var result = (from obj in dataContext.ActivityComments
                              join u in dataContext.UserInfos
                              on obj.UserID equals u.UserID
                              orderby obj.CreatedDate descending
                              where obj.ActivityID == activity.ActivityID
                              select new { obj.CommentID, obj.CommentText, obj.CreatedDate, u.FirstName, u.LastName });
                foreach (var item in result)
                {
                    model.Comments.Add(new ActivityCommentModel()
                    {
                        CommentID = item.CommentID,
                        CommentText = item.CommentText,
                        CommentedBy = string.Format("{0} {1}", item.FirstName, item.LastName),
                        TimeAgo = GetTimeAgo(item.CreatedDate)
                    });
                }

                model.ActText = activity.ActText;
            }

            return View(model);
        }

        public ActionResult Communicate()
        {
            return View();
        }

        public ActionResult DiscussionBoard()
        {
            List<DiscussionBoard> modelData = new List<DiscussionBoard>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var result = dataContext.Discussions.OrderByDescending(obj => (obj.DiscussionID));
                foreach (var item in result)
                {
                    modelData.Add(new DiscussionBoard()
                    {
                        DiscussionID = item.DiscussionID,
                        Title = item.Title,
                        Description = item.Description
                    });
                }
            }

            return View(modelData.AsEnumerable());
        }

        public ActionResult NewDiscussion()
        {
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult NewDiscussion(DiscussionBoard model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        DB.Discussion discussion = new DB.Discussion()
                        {
                            CreatedDate = DateTime.Now,
                            Description = model.Description,
                            Title = model.Title,
                            UserID = userId
                        };

                        dataContext.Discussions.InsertOnSubmit(discussion);
                        dataContext.SubmitChanges();
                        return RedirectToAction("DiscussionBoard", "faculty");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while starting discussion!");
                }
            }

            return View(model);
        }

        public ActionResult DiscussionReply(long discussionId)
        {
            DiscussionReply model = new DiscussionReply();
            model.Replies = new List<ReplyItem>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var result = dataContext.Discussions.Where(obj => (obj.DiscussionID == discussionId)).ToList();
                if (result.Count > 0)
                {
                    model.Title = result[0].Title;
                    model.Description = result[0].Description;
                    model.DiscussionID = result[0].DiscussionID;

                    var repliesResult = from dr in dataContext.DiscussionResponses
                                        join u in dataContext.UserInfos
                                        on dr.UserID equals u.UserID
                                        where dr.DiscussionID == discussionId
                                        orderby dr.CreatedDate descending
                                        select new { dr.DiscussionID, dr.ResponseText, dr.CreatedDate, u.FirstName, u.LastName };

                    foreach (var item in repliesResult)
                    {
                        model.Replies.Add(new ReplyItem()
                        {
                            CommentText = item.ResponseText,
                            RepliedDate = item.CreatedDate.ToString("dd-MMM-yyyy"),
                            ReplyBy = string.Format("{0} {1}", item.FirstName, item.LastName)
                        });
                    }
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult DiscussionReply(DiscussionReply model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        DB.DiscussionResponse discussionResponse = new DB.DiscussionResponse()
                        {
                            CreatedDate = DateTime.Now,
                            DiscussionID = model.DiscussionID,
                            ResponseText = model.Reply,
                            UserID = userId,
                        };

                        dataContext.DiscussionResponses.InsertOnSubmit(discussionResponse);
                        dataContext.SubmitChanges();

                        var result = dataContext.Discussions.Where(obj => (obj.DiscussionID == model.DiscussionID)).ToList();
                        if (result.Count > 0)
                        {
                            model.Replies = new List<ReplyItem>();
                            model.Title = result[0].Title;
                            model.Description = result[0].Description;
                            model.DiscussionID = result[0].DiscussionID;

                            var repliesResult = from dr in dataContext.DiscussionResponses
                                                join u in dataContext.UserInfos
                                                on dr.UserID equals u.UserID
                                                where dr.DiscussionID == model.DiscussionID
                                                orderby dr.CreatedDate descending
                                                select new { dr.DiscussionID, dr.ResponseText, dr.CreatedDate, u.FirstName, u.LastName };

                            foreach (var item in repliesResult)
                            {
                                model.Replies.Add(new ReplyItem()
                                {
                                    CommentText = item.ResponseText,
                                    RepliedDate = item.CreatedDate.ToString("dd-MMM-yyyy"),
                                    ReplyBy = string.Format("{0} {1}", item.FirstName, item.LastName)
                                });
                            }
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while replying the discussion!");
                }
            }

            return View(model);
        }

        public ActionResult AnswerQuery()
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            Abhimanu.Mobile.Models.AskQuery model = new Abhimanu.Mobile.Models.AskQuery();
            model.Queries = new List<Query>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var queries = from obj in dataContext.AskQueries
                              where obj.FacultyID == userId
                              orderby obj.CreatedDate descending
                              select new { obj.QueryID, obj.Message };

                foreach (var item in queries)
                {
                    model.Queries.Add(new Query()
                    {
                        Question = item.Message,
                        QueryID = item.QueryID
                    });
                }
            }

            return View(model);
        }

        public ActionResult QueryReply(long queryId)
        {
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }

            Abhimanu.Mobile.Models.AskQuery model = new Abhimanu.Mobile.Models.AskQuery();
            model.Answers = new List<Answer>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var queryList = dataContext.AskQueries.Where(obj => (obj.QueryID == queryId)).ToList();
                if (queryList.Count > 0)
                {
                    model.Subject = queryList[0].Subject;
                    model.Question = queryList[0].Message;
                    var result = dataContext.QueryAnswers.Where(obj => (obj.QueryID == queryId)).ToList();
                    if (result.Count > 0)
                    {
                        var answers = from obj in dataContext.QueryAnswers
                                      join user in dataContext.UserInfos
                                      on obj.FacultyID equals user.UserID
                                      where obj.QueryID == queryId
                                      orderby obj.CreatedDate descending
                                      select new { obj.AnswerText, obj.CreatedDate, user.FirstName, user.LastName };

                        foreach (var item in answers)
                        {
                            model.Answers.Add(new Answer()
                            {
                                AnswerText = item.AnswerText,
                                Faculty = string.Format("{0} {1}", item.FirstName, item.LastName),
                                AnswerDate = item.CreatedDate.ToString("dd-MMM-yyyy")
                            });
                        }
                    }
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult QueryReply(Abhimanu.Mobile.Models.AskQuery model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            model.Answers = new List<Answer>();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                QueryAnswer queryAns = new QueryAnswer()
                {
                    QueryID = model.QueryID,
                    FacultyID = userId,
                    AnswerText = model.Reply,
                    CreatedDate = DateTime.Now
                };

                dataContext.QueryAnswers.InsertOnSubmit(queryAns);
                dataContext.SubmitChanges();

                var queryList = dataContext.AskQueries.Where(obj => (obj.QueryID == model.QueryID)).ToList();
                if (queryList.Count > 0)
                {
                    model.Subject = queryList[0].Subject;
                    model.Question = queryList[0].Message;
                    var result = dataContext.QueryAnswers.Where(obj => (obj.QueryID == model.QueryID)).ToList();
                    if (result.Count > 0)
                    {
                        var answers = from obj in dataContext.QueryAnswers
                                      join user in dataContext.UserInfos
                                      on obj.FacultyID equals user.UserID
                                      where obj.QueryID == model.QueryID
                                      orderby obj.CreatedDate descending
                                      select new { obj.AnswerText, obj.CreatedDate, user.FirstName, user.LastName };

                        foreach (var item in answers)
                        {
                            model.Answers.Add(new Answer()
                            {
                                AnswerText = item.AnswerText,
                                Faculty = string.Format("{0} {1}", item.FirstName, item.LastName),
                                AnswerDate = item.CreatedDate.ToString("dd-MMM-yyyy")
                            });
                        }
                    }
                }
            }

            return View(model);
        }
    }
}
